package com.example.campuslink.ui.activity.userOperation

import android.content.Intent
import android.provider.MediaStore
import android.text.Editable
import android.text.TextWatcher
import android.widget.Toast
import androidx.lifecycle.lifecycleScope
import com.bumptech.glide.Glide
import com.bumptech.glide.request.RequestOptions
import com.example.campuslink.BR
import com.example.campuslink.R
import com.example.campuslink.commen.tools.PermissionManager
import com.example.campuslink.databinding.ActivityUserInfoBinding
import com.example.campuslink.ui.activity.BaseActivity
import com.example.campuslink.viewModel.userOperation.UserInfoViewModel
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch

class UserInfoActivity:BaseActivity<ActivityUserInfoBinding, UserInfoViewModel>(
    UserInfoViewModel::class.java,
    R.layout.activity_user_info,
    BR.viewModel
) {
    private val PICK_IMAGE_REQUEST = 1
    private var imgPath : String = ""

    private val permissionManager = PermissionManager(this)

    override fun initView() {
        initData()
        mViewModel?.userInfo?.observe(this){
            mViewDataBinding?.etNickName?.setText(it?.userName)
            mViewDataBinding?.etNickName?.setSelection(it?.userName?.length?:0)
            mViewDataBinding?.etRecommend?.setText(it?.userIntro)
            mViewDataBinding?.etRecommend?.setSelection(it?.userIntro?.length?:0)
            when(it?.userGender){
                "male" -> mViewDataBinding?.rbMale?.isChecked = true
                "woman" -> mViewDataBinding?.rbWoman?.isChecked = true
                else -> mViewDataBinding?.rbMale?.isChecked = true
            }

            imgPath = it?.userAvatar?:""
            mViewModel?.setImagePath(imgPath)

        }

        mViewModel?.imagePathLiveData?.observe(this){
            Glide.with(this).load(it)
                .apply(RequestOptions.circleCropTransform())
                .error(R.drawable.ic_empty)
                .into(mViewDataBinding?.ivUserImg!!)
        }
        mViewDataBinding?.ivUserImg?.setOnClickListener {
            openGallery()
        }
        mViewDataBinding?.btnUp?.setOnClickListener {
            if (mViewDataBinding?.etPassword?.text.toString() != "" && mViewDataBinding?.etRePassword?.text.toString() != ""
                && mViewDataBinding?.etPassword?.text.toString() == mViewDataBinding?.etRePassword?.text.toString()
            ) {
                val userInfo = mViewModel?.userInfo?.value
                val userNumberInfo = mViewModel?.userNumberInfo
                if (userInfo != null && userNumberInfo != null) {
                    val userName = mViewDataBinding?.etNickName?.text.toString()
                    val userIntro = mViewDataBinding?.etRecommend?.text.toString()
                    val userGender =
                        if (mViewDataBinding?.rbMale?.isChecked == true) "male" else "woman"
                    val userAvatar = imgPath
                    userInfo.userName = userName
                    userInfo.userIntro = userIntro
                    userInfo.userGender = userGender
                    userInfo.userAvatar = userAvatar
                    mViewModel?.updateUserInfo(userInfo)
                    userNumberInfo.password = mViewDataBinding?.etPassword?.text.toString()
                    mViewModel?.updateUserNumber(userNumberInfo)
                    lifecycleScope.launch(Dispatchers.Main) {
                        mViewModel?.finish()
                    }
                } else {
                    Toast.makeText(this, "请先登录", Toast.LENGTH_SHORT).show()
                }
            } else {
                Toast.makeText(this, "密码不一致或者密码为空请重新设置", Toast.LENGTH_SHORT).show()
            }

        }

        mViewDataBinding?.ivBack?.setOnClickListener {
            finish()
        }
        mViewModel?.showPassword?.observe(this) {
            if (it) {
                Glide.with(this).load(R.drawable.ic_un_display).into(mViewDataBinding?.ivDisplay!!)
            } else {
                Glide.with(this).load(R.drawable.display).into(mViewDataBinding?.ivDisplay!!)
            }
        }
        mViewModel?.againShowPassword?.observe(this) {
            if (it) {
                Glide.with(this).load(R.drawable.ic_un_display)
                    .into(mViewDataBinding?.ivDisplayAgain!!)
            } else {
                Glide.with(this).load(R.drawable.display).into(mViewDataBinding?.ivDisplayAgain!!)
            }
        }
        mViewModel?.currentPosition?.observe(this) {
            mViewDataBinding?.etPassword?.setSelection(it)
        }
        mViewModel?.againCurrentPosition?.observe(this) {
            mViewDataBinding?.etRePassword?.setSelection(it)
        }
        mViewDataBinding?.etPassword?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                mViewModel?.setCurrentPosition(p0?.length ?: 0)
            }
        })
        mViewDataBinding?.etRePassword?.addTextChangedListener(object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {

            }

            override fun afterTextChanged(p0: Editable?) {
                mViewModel?.setAgainCurrentPosition(p0?.length ?: 0)
            }
        })
    }

    private fun openGallery() {
        permissionManager.requestReadStoragePermission(this) {
            val intent = Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            startActivityForResult(intent, PICK_IMAGE_REQUEST)
        }
    }
    
    fun initData() {
        mViewModel?.context = this
        mViewModel?.initDB(this)
        mViewModel?.getUserInfo()
        mViewModel?.getUserNumber()
    }
    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == PICK_IMAGE_REQUEST && resultCode == RESULT_OK && data != null) {
            val selectedImageUri = data.data
            val projection = arrayOf(MediaStore.Images.Media.DATA)
            val contentResolver = contentResolver
            val cursor = contentResolver.query(selectedImageUri!!, projection, null, null, null)

            if (cursor != null) {
                cursor.moveToFirst()
                val columnIndex = cursor.getColumnIndex(projection[0])
                val imagePath = cursor.getString(columnIndex)
                cursor.close()

                // 此时imagePath就是所选图片的字符串形式的存储路径，可以在这里进行后续操作，如加载图片等
                imgPath = imagePath
            }
            mViewModel?.setImagePath(imagePath = imgPath)
        }
    }
}